package org.Iter6.Presentacion;

import java.awt.BorderLayout;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JScrollPane;

import java.awt.Dimension;

import javax.swing.JList;

import java.awt.Component;

import javax.swing.Box;

import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import java.awt.HeadlessException;
import java.awt.Insets;

import javax.swing.border.TitledBorder;
import javax.swing.DefaultListModel;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.ImageIcon;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.util.Enumeration;

import javax.swing.event.ListSelectionListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.border.EtchedBorder;

import org.Iter4.Presentacion.VentanaPrincipal;
import org.Iter4.Dominio.GestorDesaparecida;
import org.Iter4.Dominio.PersonaDesaparecida;

import java.awt.Color;
import java.io.File;
import java.io.PrintWriter;

public class VentanaDesaparecida extends JFrame {

	private JPanel contentPane;
	private final Component verticalStrut = Box.createVerticalStrut(24);
	private final JPanel pnlGestorPersonasBuscaCaptura = new JPanel();
	private final JScrollPane scrollPane = new JScrollPane();
	private final Component horizontalStrut = Box.createHorizontalStrut(20);
	private final JPanel panel = new JPanel();
	private final JLabel lblNombre = new JLabel("Nombre:");
	private final JLabel lblApellidos = new JLabel("Apellidos:");
	private final JLabel lblFechaNacimiento = new JLabel("Fecha Nacimiento:");
	private final JLabel lblNacion = new JLabel("Nacion:");
	private final Component horizontalStrut_1 = Box.createHorizontalStrut(20);
	private final Component verticalStrut_1 = Box.createVerticalStrut(20);
	private final JTextField txtNombre = new JTextField();
	private final JTextField txtApellidos = new JTextField();
	private final JTextField txtFechaNac = new JTextField();
	private final JTextField txtNacion = new JTextField();
	private final JPanel panel_1 = new JPanel();
	private final Component horizontalStrut_2 = Box.createHorizontalStrut(20);
	private final JButton btnAadir = new JButton("A\u00F1adir");
	private final JButton btnModificar = new JButton("Modificar");
	private final JButton btnEliminar = new JButton("Eliminar");
	private final JPanel pnlLogo = new JPanel();
	private final JLabel lblLogoDesaparecida = new JLabel("");
	private GestorDesaparecida gd;
	DefaultListModel<String> modeloLista = new DefaultListModel<String>();
	private final JList<String> listPersonasDesaparecidas = new JList<String>();
	private final JButton btnAadirFoto = new JButton("A\u00F1adir Foto");
	private final JScrollPane scrollPaneFoto = new JScrollPane();
	private final JLabel lblFoto = new JLabel("");
	private final JButton btnVolver = new JButton("Volver");
	private String url="";
	private String tipo="";
	private final JPanel panel_2 = new JPanel();
	private final JPanel panel_3 = new JPanel();
	private final JButton btnGenerarFichero = new JButton("Generar Fichero");
	
	/**
	 * Create the frame.
	 */
	public VentanaDesaparecida() {
		setResizable(false);
		
		try {
			gd=new GestorDesaparecida();
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		setPreferredSize(new Dimension(760, 450));
		setTitle("findpersons - Personas desaparecidas");
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 760, 450);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(new BorderLayout(0, 0));
		pnlLogo.setPreferredSize(new Dimension(10, 90));
		
		contentPane.add(pnlLogo, BorderLayout.NORTH);
		pnlLogo.setLayout(null);
		lblLogoDesaparecida.setIcon(new ImageIcon(VentanaDesaparecida.class.getResource("/org/Iter6/Recursos/logoPriD.png")));
		lblLogoDesaparecida.setBounds(-21, 6, 636, 72);
		
		pnlLogo.add(lblLogoDesaparecida);
		btnVolver.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				setVisible(false);
				VentanaPrincipal vp=new VentanaPrincipal();
				vp.mostrar(tipo);
				
			}
		});
		btnVolver.setBounds(627, 37, 117, 29);
		pnlLogo.add(btnVolver);
		
		contentPane.add(verticalStrut, BorderLayout.SOUTH);
		
		contentPane.add(pnlGestorPersonasBuscaCaptura, BorderLayout.CENTER);
		GridBagLayout gbl_pnlGestorUsuarios = new GridBagLayout();
		gbl_pnlGestorUsuarios.columnWidths = new int[]{0, 128, 420, 0, 0};
		gbl_pnlGestorUsuarios.rowHeights = new int[]{124, 0};
		gbl_pnlGestorUsuarios.columnWeights = new double[]{0.0, 1.0, 1.0, 0.0, Double.MIN_VALUE};
		gbl_pnlGestorUsuarios.rowWeights = new double[]{1.0, Double.MIN_VALUE};
		pnlGestorPersonasBuscaCaptura.setLayout(gbl_pnlGestorUsuarios);
		
		GridBagConstraints gbc_horizontalStrut = new GridBagConstraints();
		gbc_horizontalStrut.insets = new Insets(0, 0, 0, 5);
		gbc_horizontalStrut.gridx = 0;
		gbc_horizontalStrut.gridy = 0;
		pnlGestorPersonasBuscaCaptura.add(horizontalStrut, gbc_horizontalStrut);
		
	    Enumeration<String> e = gd.getTablaPersonasDesaparecidas().keys();
	    while(e.hasMoreElements()){
	    	modeloLista.addElement(gd.getTablaPersonasDesaparecidas().get(e.nextElement()).getID());
	    }
		
		GridBagConstraints gbc_panel_2 = new GridBagConstraints();
		gbc_panel_2.insets = new Insets(0, 0, 0, 5);
		gbc_panel_2.fill = GridBagConstraints.BOTH;
		gbc_panel_2.gridx = 1;
		gbc_panel_2.gridy = 0;
		pnlGestorPersonasBuscaCaptura.add(panel_2, gbc_panel_2);
		GridBagLayout gbl_panel_2 = new GridBagLayout();
		gbl_panel_2.columnWidths = new int[]{0, 0, 0, 0, 0};
		gbl_panel_2.rowHeights = new int[]{40, 0, 0, 0, 0, 114, 52, 0};
		gbl_panel_2.columnWeights = new double[]{0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE};
		gbl_panel_2.rowWeights = new double[]{1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE};
		panel_2.setLayout(gbl_panel_2);
		GridBagConstraints gbc_scrollPane = new GridBagConstraints();
		gbc_scrollPane.insets = new Insets(0, 0, 5, 0);
		gbc_scrollPane.gridwidth = 5;
		gbc_scrollPane.fill = GridBagConstraints.BOTH;
		gbc_scrollPane.gridheight = 6;
		gbc_scrollPane.gridx = 0;
		gbc_scrollPane.gridy = 0;
		panel_2.add(scrollPane, gbc_scrollPane);
		scrollPane.setBorder(new TitledBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null), "Personas", TitledBorder.LEADING, TitledBorder.TOP, null, new Color(0, 0, 255)));
		scrollPane.setPreferredSize(new Dimension(175, 4));
		scrollPane.setViewportView(listPersonasDesaparecidas);
		listPersonasDesaparecidas.setModel(modeloLista);
		
		GridBagConstraints gbc_panel_3 = new GridBagConstraints();
		gbc_panel_3.fill = GridBagConstraints.BOTH;
		gbc_panel_3.gridwidth = 5;
		gbc_panel_3.insets = new Insets(0, 0, 0, 5);
		gbc_panel_3.gridx = 0;
		gbc_panel_3.gridy = 6;
		panel_2.add(panel_3, gbc_panel_3);
		panel_3.setLayout(new BorderLayout(0, 0));
		btnGenerarFichero.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				
				String texto = txtNombre.getText()+txtApellidos.getText()+txtFechaNac.getText()+txtNacion.getText();
		        
		        //comprobacion si se encuentra texto
		        if (texto.matches("[[ ]*[\n]*[\t]*[-]*[_]*[*]*[(]*[\\)]]*")) {
		        	JOptionPane.showMessageDialog(null,"El fichero no tiene informacion", "Error", JOptionPane.ERROR_MESSAGE);
		        }else{
		            
		            JFileChooser fileChooser = new JFileChooser();
		            fileChooser.addChoosableFileFilter(new FileNameExtensionFilter("Fichero *.TXT", "txt","TXT"));
		            int seleccion = fileChooser.showSaveDialog(null);
		            try{
		                if (seleccion == JFileChooser.APPROVE_OPTION){
		                    File JFC = fileChooser.getSelectedFile();
		                    String PATH = JFC.getAbsolutePath();
		                    PrintWriter printwriter = new PrintWriter(JFC);
		                    printwriter.print("\nPERSONA DESAPARECIDA:");
		                    printwriter.print("\n"+txtNombre.getText());
		                    printwriter.print("\n"+txtApellidos.getText());
		                    printwriter.print("\n"+txtFechaNac.getText());
		                    printwriter.print("\n"+txtNacion.getText());
		                    printwriter.close();
		                    
		                  //comprobacion formato de archivo
		                    if(!(PATH.endsWith(".txt"))){
		                        File temp = new File(PATH+".txt");
		                        JFC.renameTo(temp);
		                    }
		                    
		                    JOptionPane.showMessageDialog(null,"Se ha guardado correctamente.", "Guardado", JOptionPane.INFORMATION_MESSAGE);
		                }
		            }catch (Exception i){
		                JOptionPane.showMessageDialog(null,"Se ha producido un error al guardar el archivo", "Error", JOptionPane.ERROR_MESSAGE);
		            }
		        }    
			}
		});
		panel_3.add(btnGenerarFichero, BorderLayout.CENTER);
		listPersonasDesaparecidas.addListSelectionListener(new ListSelectionListener() {
			public void valueChanged(ListSelectionEvent e) {
				if(gd.getTablaPersonasDesaparecidas().size()>0){
				txtNombre.setText(gd.getTablaPersonasDesaparecidas().get(listPersonasDesaparecidas.getSelectedValue()).getNombre());
				txtApellidos.setText(gd.getTablaPersonasDesaparecidas().get(listPersonasDesaparecidas.getSelectedValue()).getApellidos());
				txtFechaNac.setText(gd.getTablaPersonasDesaparecidas().get(listPersonasDesaparecidas.getSelectedValue()).getFechaNacimiento());
				txtNacion.setText(gd.getTablaPersonasDesaparecidas().get(listPersonasDesaparecidas.getSelectedValue()).getNacionalidad());
				}
			
				
			}
		});
		
		GridBagConstraints gbc_panel = new GridBagConstraints();
		gbc_panel.insets = new Insets(0, 0, 0, 5);
		gbc_panel.fill = GridBagConstraints.BOTH;
		gbc_panel.gridx = 2;
		gbc_panel.gridy = 0;
		panel.setBorder(new TitledBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null), "Ficha Persona desaparecida", TitledBorder.LEADING, TitledBorder.TOP, null, new Color(0, 0, 255)));
		pnlGestorPersonasBuscaCaptura.add(panel, gbc_panel);
		GridBagLayout gbl_panel = new GridBagLayout();
		gbl_panel.columnWidths = new int[]{0, 144, 125, 0, 0};
		gbl_panel.rowHeights = new int[]{0, 0, 0, 0, 0, 0, 0, 0};
		gbl_panel.columnWeights = new double[]{0.0, 0.0, 0.0, 1.0, Double.MIN_VALUE};
		gbl_panel.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, Double.MIN_VALUE};
		panel.setLayout(gbl_panel);
		
		GridBagConstraints gbc_verticalStrut_1 = new GridBagConstraints();
		gbc_verticalStrut_1.insets = new Insets(0, 0, 5, 5);
		gbc_verticalStrut_1.gridx = 1;
		gbc_verticalStrut_1.gridy = 0;
		panel.add(verticalStrut_1, gbc_verticalStrut_1);
		
		GridBagConstraints gbc_horizontalStrut_1 = new GridBagConstraints();
		gbc_horizontalStrut_1.insets = new Insets(0, 0, 5, 5);
		gbc_horizontalStrut_1.gridx = 0;
		gbc_horizontalStrut_1.gridy = 1;
		panel.add(horizontalStrut_1, gbc_horizontalStrut_1);
		
		GridBagConstraints gbc_scrollPaneFoto = new GridBagConstraints();
		gbc_scrollPaneFoto.gridheight = 4;
		gbc_scrollPaneFoto.insets = new Insets(0, 0, 5, 5);
		gbc_scrollPaneFoto.gridx = 1;
		gbc_scrollPaneFoto.gridy = 1;
		scrollPaneFoto.setSize(new Dimension(145, 150));
		scrollPaneFoto.setPreferredSize(new Dimension(145, 150));
		scrollPaneFoto.setMaximumSize(new Dimension(145, 150));
		scrollPaneFoto.setBorder(new TitledBorder(null, "Foto", TitledBorder.LEADING, TitledBorder.TOP, null, Color.BLUE));
		panel.add(scrollPaneFoto, gbc_scrollPaneFoto);
		lblFoto.setSize(new Dimension(125, 125));
		lblFoto.setMaximumSize(new Dimension(125, 125));
		lblFoto.setPreferredSize(new Dimension(125, 125));
		lblFoto.setIcon(new ImageIcon(VentanaDesaparecida.class.getResource("/org/Iter6/Recursos/noImagen.png")));
		
		scrollPaneFoto.setViewportView(lblFoto);
		
		GridBagConstraints gbc_lblNombre = new GridBagConstraints();
		gbc_lblNombre.anchor = GridBagConstraints.WEST;
		gbc_lblNombre.insets = new Insets(0, 0, 5, 5);
		gbc_lblNombre.gridx = 2;
		gbc_lblNombre.gridy = 1;
		panel.add(lblNombre, gbc_lblNombre);
		txtNombre.setColumns(10);
		
		GridBagConstraints gbc_txtNombre = new GridBagConstraints();
		gbc_txtNombre.fill = GridBagConstraints.HORIZONTAL;
		gbc_txtNombre.insets = new Insets(0, 0, 5, 0);
		gbc_txtNombre.gridx = 3;
		gbc_txtNombre.gridy = 1;
		panel.add(txtNombre, gbc_txtNombre);
		
		GridBagConstraints gbc_lblApellidos = new GridBagConstraints();
		gbc_lblApellidos.anchor = GridBagConstraints.WEST;
		gbc_lblApellidos.insets = new Insets(0, 0, 5, 5);
		gbc_lblApellidos.gridx = 2;
		gbc_lblApellidos.gridy = 2;
		panel.add(lblApellidos, gbc_lblApellidos);
		txtApellidos.setColumns(10);
		
		GridBagConstraints gbc_txtApellidos = new GridBagConstraints();
		gbc_txtApellidos.fill = GridBagConstraints.HORIZONTAL;
		gbc_txtApellidos.insets = new Insets(0, 0, 5, 0);
		gbc_txtApellidos.gridx = 3;
		gbc_txtApellidos.gridy = 2;
		panel.add(txtApellidos, gbc_txtApellidos);
		
		GridBagConstraints gbc_lblFechaNacimiento = new GridBagConstraints();
		gbc_lblFechaNacimiento.anchor = GridBagConstraints.WEST;
		gbc_lblFechaNacimiento.insets = new Insets(0, 0, 5, 5);
		gbc_lblFechaNacimiento.gridx = 2;
		gbc_lblFechaNacimiento.gridy = 3;
		panel.add(lblFechaNacimiento, gbc_lblFechaNacimiento);
		txtFechaNac.setColumns(10);
		
		GridBagConstraints gbc_txtFechaNac = new GridBagConstraints();
		gbc_txtFechaNac.fill = GridBagConstraints.HORIZONTAL;
		gbc_txtFechaNac.insets = new Insets(0, 0, 5, 0);
		gbc_txtFechaNac.gridx = 3;
		gbc_txtFechaNac.gridy = 3;
		panel.add(txtFechaNac, gbc_txtFechaNac);
		
		GridBagConstraints gbc_lblNacion = new GridBagConstraints();
		gbc_lblNacion.insets = new Insets(0, 0, 5, 5);
		gbc_lblNacion.anchor = GridBagConstraints.WEST;
		gbc_lblNacion.gridx = 2;
		gbc_lblNacion.gridy = 4;
		panel.add(lblNacion, gbc_lblNacion);
		txtNacion.setColumns(10);
		
		GridBagConstraints gbc_txtNacion = new GridBagConstraints();
		gbc_txtNacion.fill = GridBagConstraints.HORIZONTAL;
		gbc_txtNacion.insets = new Insets(0, 0, 5, 0);
		gbc_txtNacion.gridx = 3;
		gbc_txtNacion.gridy = 4;
		panel.add(txtNacion, gbc_txtNacion);
		
		GridBagConstraints gbc_btnAadirFoto = new GridBagConstraints();
		gbc_btnAadirFoto.insets = new Insets(0, 0, 5, 5);
		gbc_btnAadirFoto.gridx = 1;
		gbc_btnAadirFoto.gridy = 5;
		btnAadirFoto.setVisible(false);
		
		btnAadirFoto.addActionListener(new ActionListener() {
	

			public void actionPerformed(ActionEvent arg0) {
				JFileChooser fcAbrir = new JFileChooser();
				int valorDevuelto = fcAbrir.showOpenDialog(lblFoto);
				if (valorDevuelto == JFileChooser.APPROVE_OPTION) {
				File file = fcAbrir.getSelectedFile();
				System.out.println("Fichero seleccionado: " +	file.getName());
				url=file.getName();
				lblFoto.setIcon(new ImageIcon(file.getAbsolutePath()));
				}
			}
		});
		
		panel.add(btnAadirFoto, gbc_btnAadirFoto);
		panel_1.setLayout(null);
		
		GridBagConstraints gbc_panel_1 = new GridBagConstraints();
		gbc_panel_1.gridwidth = 4;
		gbc_panel_1.fill = GridBagConstraints.BOTH;
		gbc_panel_1.gridx = 0;
		gbc_panel_1.gridy = 6;
		panel.add(panel_1, gbc_panel_1);
		btnAadir.setVisible(false);
		
				
		panel_1.add(btnAadir);
		btnAadir.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				String id="";
				PersonaDesaparecida persona;
				if(txtNombre.getText()!=null&&!txtNombre.getText().equals("")&&txtApellidos.getText()!=null&&!txtApellidos.getText().equals("")&&txtNacion.getText()!=null&&!txtNacion.getText().equals("")&&txtFechaNac.getText()!=null&&!txtFechaNac.getText().equals("")){
					id=gd.siguienteID();
					persona=new PersonaDesaparecida(id,txtNombre.getText(),txtApellidos.getText(),txtFechaNac.getText(),txtNacion.getText(),url);
					url="";
					try {
						if(gd.addPersonaDesaparecida(persona)){
							modeloLista.addElement(persona.getID());
							listPersonasDesaparecidas.repaint();
						}else{
							JOptionPane.showMessageDialog(null, "El identificador ya existe.");
						}
					} catch (Exception e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
					
				}else{
					JOptionPane.showMessageDialog(null, "No puede dejar ningun campo vacio.");
				}

			}
		});
		btnAadir.setBounds(70, 31, 117, 29);
		btnModificar.setVisible(false);
		
		btnModificar.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
			
				if (listPersonasDesaparecidas.getSelectedValue() == null) {
					JOptionPane.showMessageDialog(null, "Debe seleccionar una persona.");
				}else{
				
				String id=listPersonasDesaparecidas.getSelectedValue();
				int index = listPersonasDesaparecidas.getSelectedIndex();
				int selectedIndex = calcularIndex(index,modeloLista.size());
				PersonaDesaparecida persona;
				if(txtNombre.getText()!=null&&!txtNombre.getText().equals("")&&txtApellidos.getText()!=null&&!txtApellidos.getText().equals("")&&txtNacion.getText()!=null&&!txtNacion.getText().equals("")&&txtFechaNac.getText()!=null&&!txtFechaNac.getText().equals("")){
					persona=new PersonaDesaparecida(id,txtNombre.getText(),txtApellidos.getText(),txtFechaNac.getText(),txtNacion.getText(),url);		
					
					
					try {
						if(gd.modificarPersonaDesaparecida(persona)){
							gd.consultarPersonasDesaparecidas();
						}else{
							JOptionPane.showMessageDialog(null, "No es posible modificar el usuario.");
						}
					} catch (Exception e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}

				}else{
					JOptionPane.showMessageDialog(null, "No puede dejar ningun campo vacio.");
				}
			}
				
			}
		});
		btnModificar.setBounds(199, 31, 117, 29);
		
		panel_1.add(btnModificar);
		btnEliminar.setVisible(false);
		btnEliminar.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if (listPersonasDesaparecidas.getSelectedValue() == null) {
					JOptionPane.showMessageDialog(null, "Debe seleccionar una persona.");
				}else{
					String id=listPersonasDesaparecidas.getSelectedValue();
					int index = listPersonasDesaparecidas.getSelectedIndex();
					int selectedIndex = calcularIndex(index,modeloLista.size());
					try {
						if(gd.eliminarPersonaDesaparecida(id)){
							listPersonasDesaparecidas.setSelectedIndex(selectedIndex);
							modeloLista.remove(index);
							gd.consultarPersonasDesaparecidas();
							scrollPane.revalidate();
						}else{
							JOptionPane.showMessageDialog(null, "No se puede eliminar la persona, es necesario tener al menos un usuario administrador.");
						}
					} catch (HeadlessException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					} catch (Exception e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
				}
			}
		});
		btnEliminar.setBounds(320, 31, 117, 29);
		
		panel_1.add(btnEliminar);
		
		GridBagConstraints gbc_horizontalStrut_2 = new GridBagConstraints();
		gbc_horizontalStrut_2.gridx = 3;
		gbc_horizontalStrut_2.gridy = 0;
		pnlGestorPersonasBuscaCaptura.add(horizontalStrut_2, gbc_horizontalStrut_2);
	}
	public int calcularIndex(int index,int size){
		int ind=0;
		if(index>=0&&index<size-1){
			ind=index+1;	
		}else if(index==size-1){
			ind=size-2;
		}
		return ind;
	}
	
	public void mostrar(String admin)
    {	
    	tipo=admin;
    	if(tipo.equalsIgnoreCase("administrador")){
    		btnAadir.setVisible(true);
    		btnModificar.setVisible(true);
    		btnAadirFoto.setVisible(true);
    		btnEliminar.setVisible(true);
    	}
    	
        setVisible(true);
    }
}
